from rest_framework import serializers
from .models import (
    StockAlert, StockMovement, Supplier, 
    PurchaseOrder, PurchaseOrderItem, GlobalStockSettings
)


class GlobalStockSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = GlobalStockSettings
        fields = ['default_min_stock', 'default_max_stock', 'auto_reorder']


class StockAlertSerializer(serializers.ModelSerializer):
    book_title = serializers.CharField(source='book.title', read_only=True)
    book_isbn = serializers.CharField(source='book.isbn', read_only=True)
    
    class Meta:
        model = StockAlert
        fields = [
            'id', 'book', 'book_title', 'book_isbn', 'alert_type',
            'current_stock', 'threshold', 'is_resolved', 'created_at'
        ]
        read_only_fields = ['id', 'book', 'current_stock', 'created_at']


class StockMovementSerializer(serializers.ModelSerializer):
    book_title = serializers.CharField(source='book.title', read_only=True)
    
    class Meta:
        model = StockMovement
        fields = [
            'id', 'book', 'book_title', 'movement_type', 'quantity',
            'previous_quantity', 'new_quantity', 'reference_number',
            'note', 'created_at'
        ]
        read_only_fields = ['id', 'book', 'previous_quantity', 'new_quantity', 'created_at']


class StockMovementCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = StockMovement
        fields = ['book', 'movement_type', 'quantity', 'reference_number', 'note']


class SupplierSerializer(serializers.ModelSerializer):
    class Meta:
        model = Supplier
        fields = [
            'id', 'name', 'contact_person', 'phone', 'email',
            'address', 'city', 'province', 'postal_code',
            'is_active', 'notes', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']


class PurchaseOrderItemSerializer(serializers.ModelSerializer):
    book_title = serializers.CharField(source='book.title', read_only=True)
    book_isbn = serializers.CharField(source='book.isbn', read_only=True)
    
    class Meta:
        model = PurchaseOrderItem
        fields = [
            'id', 'book', 'book_title', 'book_isbn', 'quantity',
            'unit_price', 'subtotal'
        ]
        read_only_fields = ['id', 'subtotal']


class PurchaseOrderListSerializer(serializers.ModelSerializer):
    supplier_name = serializers.CharField(source='supplier.name', read_only=True)
    items_count = serializers.SerializerMethodField()
    
    class Meta:
        model = PurchaseOrder
        fields = [
            'id', 'order_number', 'supplier', 'supplier_name',
            'total_amount', 'status', 'order_date', 'expected_date',
            'items_count', 'created_at'
        ]
    
    def get_items_count(self, obj):
        return obj.items.count()


class PurchaseOrderDetailSerializer(serializers.ModelSerializer):
    supplier = SupplierSerializer(read_only=True)
    items = PurchaseOrderItemSerializer(many=True, read_only=True)
    
    class Meta:
        model = PurchaseOrder
        fields = [
            'id', 'order_number', 'supplier', 'total_amount', 'tax_amount',
            'shipping_cost', 'status', 'order_date', 'expected_date',
            'received_date', 'notes', 'items', 'created_at'
        ]


class PurchaseOrderCreateSerializer(serializers.ModelSerializer):
    items = PurchaseOrderItemSerializer(many=True)
    
    class Meta:
        model = PurchaseOrder
        fields = ['supplier', 'expected_date', 'notes', 'items']
    
    def create(self, validated_data):
        items_data = validated_data.pop('items')
        
        # 计算总金额
        total_amount = 0
        for item_data in items_data:
            quantity = item_data['quantity']
            unit_price = item_data['unit_price']
            total_amount += quantity * unit_price
        
        # 创建采购订单
        purchase_order = PurchaseOrder.objects.create(
            total_amount=total_amount,
            **validated_data
        )
        
        # 创建订单项
        for item_data in items_data:
            PurchaseOrderItem.objects.create(
                purchase_order=purchase_order,
                **item_data
            )
        
        return purchase_order


class StockReportSerializer(serializers.Serializer):
    total_books = serializers.IntegerField()
    low_stock_books = serializers.IntegerField()
    out_of_stock_books = serializers.IntegerField()
    total_value = serializers.DecimalField(max_digits=10, decimal_places=2)
    
    class Meta:
        fields = ['total_books', 'low_stock_books', 'out_of_stock_books', 'total_value']


class SupplierReportSerializer(serializers.Serializer):
    supplier_name = serializers.CharField()
    total_orders = serializers.IntegerField()
    total_amount = serializers.DecimalField(max_digits=10, decimal_places=2)
    average_order_amount = serializers.DecimalField(max_digits=10, decimal_places=2)
    
    class Meta:
        fields = ['supplier_name', 'total_orders', 'total_amount', 'average_order_amount']
